//------------------------------------------------------------------------------
// <copyright file="UpdaterProperties.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Data;
using System.Diagnostics;

namespace DotBeer.UI.WPFClient
{
    public static class UpdaterProperties
    {
        public static readonly DependencyProperty UpdateSourceOnKeyProperty = 
            DependencyProperty.RegisterAttached("UpdateSourceOnKey",
                                                typeof(Key),
                                                typeof(TextBox),
                                                new PropertyMetadata(new PropertyChangedCallback(UpdateSourceOnKey_Changed)));

        public static void SetUpdateSourceOnKey(DependencyObject d, Key value)
        {
            d.SetValue(UpdateSourceOnKeyProperty, value);
        }

        public static Key GetUpdateSourceOnKey(DependencyObject d)
        {
            return (Key)d.GetValue(UpdateSourceOnKeyProperty);
        }

        private static void UpdateSourceOnKey_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = d as TextBox;
            textBox.KeyUp += (object sender, KeyEventArgs keyArgs) =>
            {
                if (keyArgs.Key == (Key)e.NewValue)
                {
                    BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);
                    exp.UpdateSource();

                    if (!exp.HasError)
                    {
                        UIElement focusedElement = Keyboard.FocusedElement as UIElement;
                        focusedElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                        ICommand command = textBox.GetValue(CommandProperties.CommandProperty) as ICommand;
                        command.Execute(null);
                    }
                }
            };
        }
    }
}
